#include "SocketIO.h"
#include "Socket.h"
#define MAXLINE 2048

int
HandleRequest(int sockfd);
int
main(int argc, char ** argv)
{
	int listenfd, connfd;
	pid_t childpid;
	socklen_t clilen;
	struct sockaddr_in cliaddr, serveraddr;
	listenfd = NewTCPSocket();
	serveraddr = NewTCPAddr("localhost",atoi(argv[1]));
	Bind(listenfd,(struct sockaddr*)&serveraddr, sizeof(serveraddr));
	Listen(listenfd,MAXPENDING);
	while(1){
		clilen = sizeof(cliaddr);
		connfd = Accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
		if ( (childpid = fork()) == 0 ){	//child process
			DEBUG("Child process start");
			Close(listenfd);
			HandleRequest(connfd);
			DEBUG("connfd closed ,now CHILDexiting");
			exit(0);
		}
		DEBUG("Now FATHER go to again");
		Close(connfd);
	}
}

int
HandleRequest(int sockfd)
{
	ssize_t n;
	char    buf[MAXLINE];
again:
	if ( (n = read(sockfd, buf, MAXLINE)) > 0 ){
		DEBUG("WRITE() START, N=%d",n);
		write(sockfd,buf,n);
		DEBUG("WRITE() FINISH");
	}

	if (n < 0 && errno == EINTR)
		goto again;
	else if (n < 0)
		Die("http: read error");
	return 0;
}
